﻿
namespace TestFsWeb

open System
open System.Net
open System.IO
open System.Text

module HttpListenerExtend =

    type HttpListener with
        member this.AsyncGetContext() =
            Async.FromBeginEnd(this.BeginGetContext,this.EndGetContext)

    type HttpListenerRequest with
        member this.AsyncInputString = async {
            // 'use' here will close the input stream after reading
            // but it should affect the behaviour that using the same
            // TCP connection to send back response
            // (just like shutdown one direction of the connection)
            use reader = new StreamReader(this.InputStream,this.ContentEncoding)
            return! reader.AsyncReadToEnd()
        }

    type HttpListenerResponse with
        member this.AsyncReply (text: string, ?optContentType : string) = async {
            let contentType = defaultArg optContentType "text/html; charset=UTF-8"
            try
                let buffer = Encoding.UTF8.GetBytes text
                this.ContentLength64 <- int64 buffer.Length
                this.ContentType <- contentType
                do! this.OutputStream.AsyncWrite buffer
            finally
                this.Close()// will automatically close its OutputStream
        }

        member this.AsyncReply (contentType, buffer : byte[])= async {
            try
                this.ContentLength64 <- int64 buffer.Length
                this.ContentType <- contentType
                do! this.OutputStream.AsyncWrite buffer
            finally
                this.Close()// will automatically close its OutputStream
        }

